package com.hzhr.extdevice.controller;

import com.hzhr.extdevice.mapper.device.DevCollectDataMapper;
import com.hzhr.extdevice.mapper.device.DevCollectDeviceMapper;
import com.hzhr.extdevice.mapper.device.DevIotDeviceMapper;
import com.hzhr.extdevice.mapper.device.DevMapper;
import com.hzhr.extdevice.mapper.toll.TollGasUserMapper;
import com.hzhr.extdevice.mapper.user.UserDeptMapper;
import com.hzhr.extdevice.mapper.user.UserUserMapper;
import com.hzhr.extdevice.model.database.device.DevCollectDevice;
import com.hzhr.extdevice.model.database.device.DevCollectDeviceExample;
import com.hzhr.extdevice.model.database.device.DevIotDevice;
import com.hzhr.extdevice.model.database.device.DevIotDeviceExample;
import com.hzhr.extdevice.model.database.toll.TollGasUser;
import com.hzhr.extdevice.model.database.toll.TollGasUserExample;
import com.hzhr.extdevice.model.database.user.UserDept;
import com.hzhr.extdevice.model.database.user.UserDeptExample;
import com.hzhr.extdevice.model.database.user.UserUser;
import com.hzhr.extdevice.model.database.user.UserUserExample;
import com.hzhr.extdevice.model.response.BaseResponse;
import com.hzhr.extdevice.util.StrUtil;
import com.hzhr.iot.core.constant.CommonOptions;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.report.sdk.template.ReportTemplate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;






@RestController
public class NbController
{
    @Autowired
    DevCollectDeviceMapper devCollectDeviceMapper;
    @Autowired
    DevIotDeviceMapper devIotDeviceMapper;
    @Autowired
    DevCollectDataMapper devCollectDataMapper;
    @Autowired
    UserUserMapper userUserMapper;
    @Autowired
    UserDeptMapper userDeptMapper;
    @Autowired
    TollGasUserMapper tollGasUserMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    DevMapper devMapper;

    private final String MESSAGE_NBDEVICEID_FORMAT_ERROR = "表号格式错误(表号必须为14位数字)！";
    private final String MESSAGE_NBDEVICEID_CONTENT_ERROR = "表号错误，请输入正确的表号！如果确认表号输入准确无误，请联系管理员！";

    private Logger logger = LoggerFactory.getLogger(NbController.class);

    @RequestMapping(value = {"/nb/sell"}, method = {RequestMethod.POST})
    @ResponseBody
    public Object post(@RequestBody Map<String, Object> param) throws Exception {
        try {
            String nbCode = "1";

            Map<String, Object> body = (Map)param.get("iotDevice");

            DevIotDevice iotDeviceEntity = new DevIotDevice();
            if (body.get("deviceid") != null) {
                iotDeviceEntity.setCode(body.get("deviceid").toString());
            } else {
                return new BaseResponse("10101", "该设备无设备编号，无法分配！");
            }
            String deviceid = body.get("deviceid").toString();
            DevIotDeviceExample example = new DevIotDeviceExample();
            example.createCriteria().andCodeEqualTo(deviceid).andCategoryCodeEqualTo(nbCode).andIsValidEqualTo("1");
            int count = this.devIotDeviceMapper.countByExample(example);
            if (count > 0) {
                return new BaseResponse("10102", "燃气公司已存在该设备，无法分配！");
            }

            iotDeviceEntity.setCategoryCode(nbCode);
            if (body.get("des") != null) {
                iotDeviceEntity.setDes(body.get("des").toString());
            }
            if (body.get("address") != null) {
                iotDeviceEntity.setAddress(body.get("address").toString());
            }
            if (body.get("longitude") != null) {
                iotDeviceEntity.setLongitude(Double.valueOf(Double.parseDouble(body.get("longitude").toString())));
            }
            if (body.get("latitude") != null) {
                iotDeviceEntity.setLatitude(Double.valueOf(Double.parseDouble(body.get("latitude").toString())));
            }
            iotDeviceEntity.setIotPlatformCode("1");
            if (body.get("nbserialnum") != null) {
                iotDeviceEntity.setIotPlatformDeviceId(body.get("nbserialnum").toString());
            }
            if (body.get("nbidentity") != null) {
                iotDeviceEntity.setIotPlatformImei(body.get("nbidentity").toString());
            }
            if (body.get("sim") != null) {
                iotDeviceEntity.setSimNo(body.get("sim").toString());
            }
            if (body.get("iotcompanyId") != null) {
                String iotCompanyId = body.get("iotcompanyId").toString();
                if (iotCompanyId.equals("8")) {
                    iotDeviceEntity.setCompanyId(Integer.valueOf(35));
                } else if (iotCompanyId.equals("12")) {
                    iotDeviceEntity.setCompanyId(Integer.valueOf(29));
                } else if (iotCompanyId.equals("14")) {
                    iotDeviceEntity.setCompanyId(Integer.valueOf(50));
                } else if (iotCompanyId.equals("15")) {
                    iotDeviceEntity.setCompanyId(Integer.valueOf(33));
                } else if (iotCompanyId.equals("16")) {
                    iotDeviceEntity.setCompanyId(Integer.valueOf(33));
                } else if (iotCompanyId.equals("18")) {
                    iotDeviceEntity.setCompanyId(Integer.valueOf(54));
                } else if (iotCompanyId.equals("19")) {
                    iotDeviceEntity.setCompanyId(Integer.valueOf(47));
                } else if (iotCompanyId.equals("20")) {
                    iotDeviceEntity.setCompanyId(Integer.valueOf(44));
                }
            }
            iotDeviceEntity.setGasCompanyId(Integer.valueOf(9));
            iotDeviceEntity.setDeptId(Integer.valueOf(2));
            if (body.get("reporttime") != null) {
                iotDeviceEntity.setReportTime(body.get("reporttime").toString());
            }
            if (body.get("reportperiod") != null) {
                String reportperiod = body.get("reportperiod").toString();
                if (reportperiod.equals("10000361")) {
                    iotDeviceEntity.setReportPeriod("2");
                } else if (reportperiod.equals("10000372")) {
                    iotDeviceEntity.setReportPeriod("1");
                }
            }
            if (body.get("bindstatus") != null) {
                String bindstatus = body.get("bindstatus").toString();
                if (bindstatus.equals("10000381")) {
                    iotDeviceEntity.setBindStatus(CommonOptions.YES_NO.YES);
                } else if (bindstatus.equals("10000392")) {
                    iotDeviceEntity.setBindStatus(CommonOptions.YES_NO.NO);
                }
            }
            iotDeviceEntity.setResourceCode("01000901");
            iotDeviceEntity.setCreateTime(new Date());
            iotDeviceEntity.setCreateUserId(Integer.valueOf(0));
            iotDeviceEntity.setIsValid(CommonOptions.YES_NO.YES);
            iotDeviceEntity.setState("1");

            this.devIotDeviceMapper.insert(iotDeviceEntity);

            return new BaseResponse("0", "成功", "");
        } catch (Exception e) {
            e.printStackTrace();
            BaseResponse result = new BaseResponse("500", "未知异常！");
            return result;
        }
    }

    @RequestMapping(value = "/nb-iotmeter/add", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse addNbmeter(@RequestParam(value = "collectdevice-deviceid", required = false) String collectdeviceDeviceid,
                                   @RequestParam(value = "collectdevice-address", required = false) String collectdeviceAddress,
                                   @RequestParam(value = "collectdevice-model", required = false) String collectdeviceModel,
                                   @RequestParam(value = "collectdevice-des", required = false) String collectdeviceDes,

                                   @RequestParam(value = "gasuser-no", required = false) String gasuserNo,
                                   @RequestParam(value = "gasuser-name", required = false) String gasuserName,
                                   @RequestParam(value = "gasuser-address", required = false) String gasuserAddress,
                                   @RequestParam(value = "gasuser-phone", required = false) String gasuserPhone,
                                   @RequestParam(value = "gasuser-type", required = false) String gasuserType,
                                   @RequestParam(value = "gasuser-bmcode", required = false) String gasuserBmcode,

                                   @RequestParam(value = "operator-username", required = false) String operatorUsername,
                                   @RequestParam(value = "operator-bmcode", required = false) String operatorBmcode) throws  Exception {
        logger.info("建档开始：" + collectdeviceDeviceid);

        if (collectdeviceDeviceid.length() != 14) return new BaseResponse("102", MESSAGE_NBDEVICEID_FORMAT_ERROR);

        DevIotDeviceExample example = new DevIotDeviceExample();
        example.createCriteria().andCodeEqualTo(collectdeviceDeviceid).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
        List<DevIotDevice> iotDevices = this.devIotDeviceMapper.selectByExample(example);
        if (iotDevices.size() == 0) {
            return new BaseResponse("101", MESSAGE_NBDEVICEID_CONTENT_ERROR);
        }
        DevIotDevice iotDevice = (DevIotDevice)iotDevices.get(0);

        try {
            UserUserExample example1 = new UserUserExample();
            example1.createCriteria().andUserNameEqualTo(operatorUsername);
            List<UserUser> userEntityList = this.userUserMapper.selectByExample(example1);
            Integer userId = null;
            if (userEntityList.size() > 0) {
                userId = ((UserUser)userEntityList.get(0)).getId();
            }


            TollGasUser gasuser = null;

            TollGasUserExample example2 = new TollGasUserExample();
            example2.createCriteria().andCodeEqualTo(gasuserNo).andIsValidEqualTo("1");
            List<TollGasUser> gasusers = this.tollGasUserMapper.selectByExample(example2);
            TollGasUser oriGasuser = (gasusers.size() > 0) ? (TollGasUser)gasusers.get(0) : null;
            if (oriGasuser == null) {
                gasuser = new TollGasUser();
                gasuser.setCode(gasuserNo);
                gasuser.setName(gasuserName);
                gasuser.setAddress(gasuserAddress);
                gasuser.setPhone(HzhrTypeUtil.string2long(gasuserPhone));
                if ("1".equals(gasuserType)) {
                    gasuser.setTypeCode("2");
                } else if ("2".equals(gasuserType)) {
                    gasuser.setTypeCode("1");
                }
                gasuser.setCompanyId(Integer.valueOf(9));
                UserDept dept = getDeptByBmCode(gasuserBmcode);
                gasuser.setDeptId(dept.getId());
                gasuser.setIsValid("1");
                gasuser.setState("1");
                gasuser.setCreateTime(new Date());
                gasuser.setCreateUserId(userId);
                gasuser.setResourceCode(dept.getResourceCode());
                this.tollGasUserMapper.insert(gasuser);
            } else {
                gasuser = oriGasuser;
                gasuser.setCode(gasuserNo);
                gasuser.setName(gasuserName);
                gasuser.setAddress(gasuserAddress);
                gasuser.setPhone(HzhrTypeUtil.string2long(gasuserPhone));
                if ("1".equals(gasuserType)) {
                    gasuser.setTypeCode("2");
                } else if ("2".equals(gasuserType)) {
                    gasuser.setTypeCode("1");
                }
                gasuser.setCompanyId(Integer.valueOf(9));
                UserDept dept = getDeptByBmCode(gasuserBmcode);
                gasuser.setDeptId(dept.getId());
                gasuser.setUpdateTime(new Date());
                gasuser.setUpdateUserId(userId);
                gasuser.setResourceCode(dept.getResourceCode());
                this.tollGasUserMapper.updateByPrimaryKey(gasuser);
            }


            DevCollectDevice collectdeviceEntity = null;

            DevCollectDeviceExample example3 = new DevCollectDeviceExample();
            example3.createCriteria().andCodeEqualTo(collectdeviceDeviceid).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
            List<DevCollectDevice> devCollectDevices = this.devCollectDeviceMapper.selectByExample(example3);
            DevCollectDevice oriCollectdevice = (devCollectDevices.size() > 0) ? (DevCollectDevice)devCollectDevices.get(0) : null;
            if (oriCollectdevice == null) {
                collectdeviceEntity = new DevCollectDevice();
                collectdeviceEntity.setCode(collectdeviceDeviceid);
                collectdeviceEntity.setCategoryCode("1");
                collectdeviceEntity.setInstallAddress(collectdeviceAddress);
                collectdeviceEntity.setDes(collectdeviceDes);
                collectdeviceEntity.setInstallTime(new Date());
                collectdeviceEntity.setCompanyId(Integer.valueOf(9));
                collectdeviceEntity.setGasUserId(gasuser.getId());
                collectdeviceEntity.setGasUserName(gasuser.getName());
                collectdeviceEntity.setGasUserAddress(gasuser.getAddress());
                collectdeviceEntity.setGasUserCode(gasuser.getCode());
                UserDept operatorDept = getDeptByBmCode(operatorBmcode);
                collectdeviceEntity.setDeptId(operatorDept.getId());
                collectdeviceEntity.setDeptCode(operatorDept.getCode());
                collectdeviceEntity.setIotDeviceId(iotDevice.getId());
                collectdeviceEntity.setCreateTime(new Date());
                collectdeviceEntity.setCreateUserId(userId);
                collectdeviceEntity.setResourceCode(operatorDept.getResourceCode());
                if (!StringUtils.isEmpty(collectdeviceModel)) {
                    Integer typeId = devMapper.select2(collectdeviceModel);
                    if (typeId != null) {
                        collectdeviceEntity.setTypeId(typeId);
                    }
                }
                collectdeviceEntity.setIsValid("1");
                collectdeviceEntity.setState("1");

                this.devCollectDeviceMapper.insert(collectdeviceEntity);
            } else {
                collectdeviceEntity = oriCollectdevice;
                collectdeviceEntity.setCode(collectdeviceDeviceid);
                collectdeviceEntity.setInstallAddress(collectdeviceAddress);
                collectdeviceEntity.setDes(collectdeviceDes);
                collectdeviceEntity.setInstallTime(new Date());
                collectdeviceEntity.setCompanyId(Integer.valueOf(9));
                collectdeviceEntity.setGasUserId(gasuser.getId());
                collectdeviceEntity.setGasUserName(gasuser.getName());
                collectdeviceEntity.setGasUserAddress(gasuser.getAddress());
                collectdeviceEntity.setGasUserCode(gasuser.getCode());
                UserDept operatorDept = getDeptByBmCode(operatorBmcode);
                collectdeviceEntity.setDeptId(operatorDept.getId());
                collectdeviceEntity.setDeptCode(operatorDept.getCode());
                collectdeviceEntity.setIotDeviceId(iotDevice.getId());
                collectdeviceEntity.setUpdateTime(new Date());
                collectdeviceEntity.setUpdateUserId(userId);
                collectdeviceEntity.setResourceCode(operatorDept.getResourceCode());
                if (!StringUtils.isEmpty(collectdeviceModel)) {
                    Integer typeId = devMapper.select2(collectdeviceModel);
                    if (typeId != null) {
                        collectdeviceEntity.setTypeId(typeId);
                    }
                }
                collectdeviceEntity.setIsValid("1");
                collectdeviceEntity.setState("1");

                this.devCollectDeviceMapper.updateByPrimaryKey(collectdeviceEntity);
            }
            return new BaseResponse("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse("100", "失败：未知错误，请联系管理员！");
        }
    }

    @RequestMapping(value = "/nb-iotmeter/edit-deviceid", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse editNbmeter(@RequestParam(value = "collectdevice-olddeviceid", required = true) String collectdeviceOlddeviceid,
                                    @RequestParam(value = "collectdevice-newdeviceid", required = true) String collectdeviceNewdeviceid,
                                    @RequestParam(value = "operator-username", required = true) String operatorUsername) throws  Exception {
        logger.info("更改表号开始：" + collectdeviceOlddeviceid + "->" + collectdeviceNewdeviceid);

        if (collectdeviceOlddeviceid.length() != 14) return new BaseResponse("102", MESSAGE_NBDEVICEID_FORMAT_ERROR + "(旧表号)");
        if (collectdeviceNewdeviceid.length() != 14) return new BaseResponse("102", MESSAGE_NBDEVICEID_FORMAT_ERROR + "(新表号)");

        try {
            DevCollectDeviceExample example = new DevCollectDeviceExample();
            example.createCriteria().andCodeEqualTo(collectdeviceOlddeviceid).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
            List<DevCollectDevice> devCollectDevices = this.devCollectDeviceMapper.selectByExample(example);
            DevCollectDevice oldCollectdevice = (devCollectDevices.size() > 0) ? (DevCollectDevice)devCollectDevices.get(0) : null;
            DevCollectDeviceExample example1 = new DevCollectDeviceExample();
            example1.createCriteria().andCodeEqualTo(collectdeviceNewdeviceid).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
            List<DevCollectDevice> devCollectDevices1 = this.devCollectDeviceMapper.selectByExample(example1);
            DevCollectDevice newCollectdevice = (devCollectDevices1.size() > 0) ? (DevCollectDevice)devCollectDevices.get(0) : null;

            if (oldCollectdevice == null) return new BaseResponse("101", "表号错误：旧表不存在");
            if (newCollectdevice != null) return new BaseResponse("101", "表号错误：新表号已存在");

            UserUserExample userExample = new UserUserExample();
            userExample.createCriteria().andUserNameEqualTo(operatorUsername);
            List<UserUser> userEntityList = this.userUserMapper.selectByExample(userExample);
            Integer userId = null;
            if (userEntityList.size() > 0) {
                userId = ((UserUser)userEntityList.get(0)).getId();
            }

            oldCollectdevice.setCode(collectdeviceNewdeviceid);
            oldCollectdevice.setUpdateUserId(userId);
            oldCollectdevice.setUpdateTime(new Date());
            this.devCollectDeviceMapper.updateByPrimaryKey(oldCollectdevice);
            return new BaseResponse("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse("100", "失败：未知错误，请联系管理员！");
        }
    }

    @RequestMapping(value = "/nb-iotmeter/del", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse delNbmeter(@RequestParam(value = "collectdevice-deviceid", required = true) String collectdevicedeviceid,
                                   @RequestParam(value = "operator-username", required = true) String operatorUsername) throws  Exception {
        logger.info("拆除开始：" + collectdevicedeviceid);

        DevCollectDeviceExample example = new DevCollectDeviceExample();
        example.createCriteria().andCodeEqualTo(collectdevicedeviceid).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
        List<DevCollectDevice> devCollectDevices = this.devCollectDeviceMapper.selectByExample(example);
        DevCollectDevice oldCollectdevice = (devCollectDevices.size() > 0) ? (DevCollectDevice)devCollectDevices.get(0) : null;
        if (oldCollectdevice == null) return new BaseResponse("0", "成功");

        try {
            UserUserExample userExample = new UserUserExample();
            userExample.createCriteria().andUserNameEqualTo(operatorUsername);
            List<UserUser> userEntityList = this.userUserMapper.selectByExample(userExample);
            Integer userId = null;
            if (userEntityList.size() > 0) {
                userId = ((UserUser)userEntityList.get(0)).getId();
            }

            oldCollectdevice.setIsValid(CommonOptions.YES_NO.NO);
            oldCollectdevice.setUpdateUserId(userId);
            oldCollectdevice.setUpdateTime(new Date());
            this.devCollectDeviceMapper.updateByPrimaryKey(oldCollectdevice);
            return new BaseResponse("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse("100", "失败：未知错误，请联系管理员！");
        }
    }

    @RequestMapping(value = "/nb-iotmeter/replace", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse replaceNbmeter(@RequestParam(value = "collectdevice-olddeviceid", required = false) String collectdeviceOlddeviceid,
                                       @RequestParam(value = "collectdevice-newdeviceid", required = true) String collectdeviceNewdeviceid,
                                       @RequestParam(value = "collectdevice-address", required = false) String collectdeviceAddress,
                                       @RequestParam(value = "collectdevice-model", required = false) String collectdeviceModel,
                                       @RequestParam(value = "collectdevice-des", required = false) String collectdeviceDes,

                                       @RequestParam(value = "gasuser-no", required = true) String gasuserNo,
                                       @RequestParam(value = "gasuser-name", required = false) String gasuserName,
                                       @RequestParam(value = "gasuser-address", required = false) String gasuserAddress,
                                       @RequestParam(value = "gasuser-phone", required = false) String gasuserPhone,
                                       @RequestParam(value = "gasuser-type", required = false) String gasuserType,
                                       @RequestParam(value = "gasuser-bmcode", required = false) String gasuserBmcode,

                                       @RequestParam(value = "operator-username", required = true) String operatorUsername,
                                       @RequestParam(value = "operator-bmcode", required = true) String operatorBmcode) throws  Exception {
        logger.info("换表开始：" + collectdeviceOlddeviceid + "->" + collectdeviceNewdeviceid);

        DevCollectDeviceExample example = new DevCollectDeviceExample();
        example.createCriteria().andCodeEqualTo(collectdeviceOlddeviceid).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
        List<DevCollectDevice> devCollectDevices = this.devCollectDeviceMapper.selectByExample(example);
        DevCollectDevice oldCollectdevice = (devCollectDevices.size() > 0) ? (DevCollectDevice)devCollectDevices.get(0) : null;
        if (collectdeviceNewdeviceid.length() != 14) return new BaseResponse("102", MESSAGE_NBDEVICEID_FORMAT_ERROR);
        DevIotDeviceExample example1 = new DevIotDeviceExample();
        example1.createCriteria().andCodeEqualTo(collectdeviceNewdeviceid).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
        List<DevIotDevice> iotDevices = this.devIotDeviceMapper.selectByExample(example1);
        DevIotDevice iotDevice = (iotDevices.size() > 0) ? (DevIotDevice)iotDevices.get(0) : null;
        if (iotDevice == null) return new BaseResponse("101", MESSAGE_NBDEVICEID_CONTENT_ERROR);

        try {
            UserUserExample userExample = new UserUserExample();
            userExample.createCriteria().andUserNameEqualTo(operatorUsername);
            List<UserUser> userEntityList = this.userUserMapper.selectByExample(userExample);
            Integer adminId = null;
            if (userEntityList.size() > 0) {
                adminId = ((UserUser)userEntityList.get(0)).getId();
            }


            if (oldCollectdevice != null) {
                oldCollectdevice.setIsValid(CommonOptions.YES_NO.NO);
                oldCollectdevice.setUpdateUserId(adminId);
                oldCollectdevice.setUpdateTime(new Date());
                this.devCollectDeviceMapper.updateByPrimaryKey(oldCollectdevice);
            }



            TollGasUser gasuser = null;

            TollGasUserExample example2 = new TollGasUserExample();
            example2.createCriteria().andCodeEqualTo(gasuserNo).andIsValidEqualTo("1");
            List<TollGasUser> gasusers = this.tollGasUserMapper.selectByExample(example2);
            TollGasUser oriGasuser = (gasusers.size() > 0) ? (TollGasUser)gasusers.get(0) : null;
            if (oriGasuser == null) {
                gasuser = new TollGasUser();
                gasuser.setCode(gasuserNo);
                gasuser.setName(gasuserName);
                gasuser.setAddress(gasuserAddress);
                gasuser.setPhone(HzhrTypeUtil.string2long(gasuserPhone));
                if ("1".equals(gasuserType)) {
                    gasuser.setTypeCode("2");
                } else if ("2".equals(gasuserType)) {
                    gasuser.setTypeCode("1");
                }
                gasuser.setCompanyId(Integer.valueOf(9));
                UserDept dept = getDeptByBmCode(gasuserBmcode);
                gasuser.setDeptId(dept.getId());
                gasuser.setIsValid("1");
                gasuser.setState("1");
                gasuser.setCreateTime(new Date());
                gasuser.setCreateUserId(adminId);
                gasuser.setResourceCode(dept.getResourceCode());
                this.tollGasUserMapper.insert(gasuser);
            } else {
                gasuser = oriGasuser;
                gasuser.setCode(gasuserNo);
                gasuser.setName(gasuserName);
                gasuser.setAddress(gasuserAddress);
                gasuser.setPhone(HzhrTypeUtil.string2long(gasuserPhone));
                if ("1".equals(gasuserType)) {
                    gasuser.setTypeCode("2");
                } else if ("2".equals(gasuserType)) {
                    gasuser.setTypeCode("1");
                }
                gasuser.setCompanyId(Integer.valueOf(9));
                UserDept dept = getDeptByBmCode(gasuserBmcode);
                gasuser.setDeptId(dept.getId());
                gasuser.setUpdateTime(new Date());
                gasuser.setUpdateUserId(adminId);
                gasuser.setResourceCode(dept.getResourceCode());
                this.tollGasUserMapper.updateByPrimaryKey(gasuser);
            }


            DevCollectDevice collectdeviceEntity = null;

            DevCollectDeviceExample example3 = new DevCollectDeviceExample();
            example3.createCriteria().andCodeEqualTo(collectdeviceNewdeviceid).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
            devCollectDevices = this.devCollectDeviceMapper.selectByExample(example3);
            DevCollectDevice oriCollectdevice = (devCollectDevices.size() > 0) ? (DevCollectDevice)devCollectDevices.get(0) : null;
            if (oriCollectdevice == null) {
                collectdeviceEntity = new DevCollectDevice();
                collectdeviceEntity.setCode(collectdeviceNewdeviceid);
                collectdeviceEntity.setCategoryCode("1");
                collectdeviceEntity.setInstallAddress(collectdeviceAddress);
                collectdeviceEntity.setDes(collectdeviceDes);
                collectdeviceEntity.setInstallTime(new Date());
                collectdeviceEntity.setCompanyId(Integer.valueOf(9));
                collectdeviceEntity.setGasUserId(gasuser.getId());
                collectdeviceEntity.setGasUserName(gasuser.getName());
                collectdeviceEntity.setGasUserAddress(gasuser.getAddress());
                collectdeviceEntity.setGasUserCode(gasuser.getCode());
                UserDept operatorDept = getDeptByBmCode(operatorBmcode);
                collectdeviceEntity.setDeptId(operatorDept.getId());
                collectdeviceEntity.setDeptCode(operatorDept.getCode());
                collectdeviceEntity.setIotDeviceId(iotDevice.getId());
                collectdeviceEntity.setCreateTime(new Date());
                collectdeviceEntity.setCreateUserId(adminId);
                collectdeviceEntity.setResourceCode(operatorDept.getResourceCode());
                if (!StringUtils.isEmpty(collectdeviceModel)) {
                    Integer typeId = devMapper.select2(collectdeviceModel);
                    if (typeId != null) {
                        collectdeviceEntity.setTypeId(typeId);
                    }
                }
                collectdeviceEntity.setIsValid("1");
                collectdeviceEntity.setState("1");

                this.devCollectDeviceMapper.insert(collectdeviceEntity);
            } else {
                collectdeviceEntity = oriCollectdevice;
                collectdeviceEntity.setCode(collectdeviceNewdeviceid);
                collectdeviceEntity.setInstallAddress(collectdeviceAddress);
                collectdeviceEntity.setDes(collectdeviceDes);
                collectdeviceEntity.setInstallTime(new Date());
                collectdeviceEntity.setCompanyId(Integer.valueOf(9));
                collectdeviceEntity.setGasUserId(gasuser.getId());
                collectdeviceEntity.setGasUserName(gasuser.getName());
                collectdeviceEntity.setGasUserAddress(gasuser.getAddress());
                collectdeviceEntity.setGasUserCode(gasuser.getCode());
                UserDept operatorDept = getDeptByBmCode(operatorBmcode);
                collectdeviceEntity.setDeptId(operatorDept.getId());
                collectdeviceEntity.setDeptCode(operatorDept.getCode());
                collectdeviceEntity.setIotDeviceId(iotDevice.getId());
                collectdeviceEntity.setUpdateTime(new Date());
                collectdeviceEntity.setUpdateUserId(adminId);
                collectdeviceEntity.setResourceCode(operatorDept.getResourceCode());
                if (!StringUtils.isEmpty(collectdeviceModel)) {
                    Integer typeId = devMapper.select2(collectdeviceModel);
                    if (typeId != null) {
                        collectdeviceEntity.setTypeId(typeId);
                    }
                }
                collectdeviceEntity.setIsValid("1");
                collectdeviceEntity.setState("1");

                this.devCollectDeviceMapper.updateByPrimaryKey(collectdeviceEntity);
            }
            return new BaseResponse("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse("100", "失败：未知错误，请联系管理员！");
        }
    }


    private Map<String, Object> convertMapKey(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = (String)entry.getKey();
            result.put(StrUtil.zhuanTuoFeng(key, "_"), entry.getValue());
        }
        return result;
    }
    private UserDept getDeptByBmCode(String bmCode) {
        if (bmCode == null) return null;
        if (bmCode.length() < 4) return null;
        if ("0000".equals(bmCode)) {
            UserDeptExample example = new UserDeptExample();
            example.createCriteria().andCodeEqualTo("9-01");
            List<UserDept> deptEntityList = this.userDeptMapper.selectByExample(example);
            if (deptEntityList.size() > 0) return (UserDept)deptEntityList.get(0);
        }
        String deptCode = bmCode.replaceFirst("0000", "9-01");
        UserDeptExample example = new UserDeptExample();
        example.createCriteria().andCodeEqualTo(deptCode);
        List<UserDept> deptEntityList = this.userDeptMapper.selectByExample(example);
        if (deptEntityList.size() > 0) return (UserDept)deptEntityList.get(0);
        return null;
    }
}
